package com.example.wtt.utils;

import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.wtt.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;

public class TokenUtils {

    private static UserService staticUserService;
    @Resource
    private UserService userService;
    @PostConstruct
    public void setUserService(){
        staticUserService = userService;
    }

    /**
     * 生成token
     */
    public static String genToken(String userId, String password){
        return JWT.create().withAudience(userId) // 将 user id 保存到 token 里面,作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期
                .sign(Algorithm.HMAC256(password)); // 以 password 作为 token 的密钥
//        return Jwts.builder()
//                .setHeaderParam("type","JWT")
//                .setAudience(userId)
//                .setExpiration(DateUtil.offsetHour(new Date(),2))
//                .signWith(SignatureAlgorithm.ES256,password)
//                .compact();
    }
    /**
     * 获取当前登录的用户信息
     *
     * @return user对象
     */
//    public static User getCurrentUser() {
//        try {
//            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//            String token = request.getHeader("token");
//            if (StrUtil.isNotBlank(token)) {
//                String userId = JWT.decode(token).getAudience().get(0);
//                return staticUserService.getById(Integer.valueOf(userId));
//            }
//        } catch (Exception e) {
//            return null;
//        }
//        return null;
//    }
}
